// Initialize app
var myApp = new Framework7({
    //template7Pages: true, //enable Template7 rendering for pages
    //Specify templates/pages data
    precompileTemplates: true,
    template7Pages: true,
});
// If we need to use custom DOM library, let's save it to $$ variable:
var $$ = Framework7.$;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we want to use dynamic navbar, we need to enable it for this view:
    dynamicNavbar: true,
})

var currentPage = 1;
var alreadyAlert = true;
var queryParas = {
    PageSize: 10,
    PageNumber: 1,
}
var visaChildId= 0 ;//初始化
$$(document).on('pageAfterAnimation', function (e) {
    var pageName = e.detail.page.name;
    if (pageName === 'index') {
        $("#index-tool").html("").removeClass("toolbar");
        App.hideSellerShop();
        myApp.hideToolbar();
    }else if (pageName === 'detail') {
        var toolbarHtml = '<div class="toolbar-inner" style="text-align: center;padding:0px">' +
            '<a style="width:20%;" onclick="App.requestVisaInfo(\'email\')"><img src="' + Constant.cdnContentPath + '/static/image/detail/email-2x.png" height="25"/></a>' +
            '<a style="width:20%;" onclick="App.requestVisaInfo(\'phone\')"><img src="' + Constant.cdnContentPath + '/static/image/detail/phone-2x.png" height="25"/></a>' +
            '<a style="width:20%;" onclick="alert(\'正在开发中\')"><img id="collection-img" src="' + Constant.cdnContentPath + '/static/image/detail/collection-2x-false.png" height="25"/></a>' +
            '<a id="ticket-reserve" style="width:45%;height:60px;background-color: #509AF1;line-height: 60px;color: #FFFFFF;">商品选购</a>' +
            '</div>';
        $("#index-tool").addClass("toolbar").html(toolbarHtml);
        $("#ticket-reserve").attr("href", "/view/menu2/visa/reserve.jsp");
        mainView.showToolbar();
    } else if(pageName === 'reserve'){
        var toolbarHtml = '<div class="toolbar-inner" style="text-align: center;padding:0px">' +
            '<div style="width:50%;">原价:<s style="color:#b7b7be"><span id="lastPriceOld">0</span>元</s><br/>现价:<span style=" color:red"><span id="lastPrice">0</span>元</span></div>' +
            '<a id="ticket-reserve" style="width:50%;height:60px;background-color: #509AF1;line-height: 60px;color: #FFFFFF;">现在预定</a>' +
            '</div>';
        $("#index-tool").addClass("toolbar").html(toolbarHtml);
        $("#ticket-reserve").attr("href", "/view/menu2/visa/collect_info.jsp");
        mainView.showToolbar();
    }else if(pageName === 'collect'){
        $("#ticket-reserve").attr("href", "#").on("click",saveVisaOrder);
        $("#collect_amount").on("change", function () {
            var tt = $("#collect_amount").val() * ($("#lastPrice").html());
            $("#lastPrice").html(tt);
        })
    }
});

$$(document).on('pageInit', function (e) {
    // Get page data from event data
    var page = e.detail.page;
    if (page.name === 'index') {
        onEvent();
        addSearchResult(queryParas, "refresh");
    } else if (page.name === 'detail') {
        var targetId = $("#detail-targetId").val();
        var para = {
            typeId: 17,
            visaId: targetId,
            targetId: targetId
        }
        App.getPhoto(para);
        var queryUrl = Constant.ctx('/mulanweb/common/visa/getVisaDetail');
        $.post(queryUrl, para, function (info) {
            if (info.ReturnCode == 1) {
                var moduleDetailHtml = $("#visaDetailModule").html();
                var compiledTemplate = Template7.compile(moduleDetailHtml);
                var newDetailHtml = compiledTemplate(info.DataList);
                $("#ticket-detail").append(newDetailHtml);
                $("#ticket-score").html(info.DataList.Score);
            }
        });

        /*var evaluatePara = {
         targetId: targetId,
         typeId: 23,
         PageSize: 10,
         PageNumber: 1
         }
         App.getEvaluates(evaluatePara)//添加评论列表*/
        App.hideLoading();
    }else if (page.name === 'reserve') {
        var queryUrl = Constant.ctx('/mulanweb/common/visa/getVisaChild');
        var visaId = $("#detail-targetId").val();
        $.post(queryUrl, {visaId:visaId}, function (info) {
            if (info.ReturnCode == 1) {
                var moduleDetailHtml = $("#visaChildListModel").html();
                var compiledTemplate = Template7.compile(moduleDetailHtml);
                var newDetailHtml = compiledTemplate(info);
                $("#visa_child").html(newDetailHtml);
            }
        });
    }
})

function onEvent() {
    var para = {
        PageSize: 10,
        PageNumber: 1,
    };
    //上拉无限加载
    var loading = false;
    // 添加'infinite'监听器
    $$('.infinite-scroll').on('infinite', function () {
        if (loading) return;
        // 设置flag
        loading = true;
        currentPage = currentPage + 1;
        para.PageNumber = currentPage;
        addSearchResult(para);
        loading = false;
    });

    // 添加'refresh'监听器
    $$('.pull-to-refresh-content').on('refresh', function (e) {
        para.PageNumber = 1;
        para.PageSize = 10;
        if (!alreadyAlert) {
            alreadyAlert = true;
            var html = '<div class="infinite-scroll-preloader">' +
                '<div class="preloader" style="margin-left:48%"></div>' +
                '</div>';
            $$('.page-content').append(html);
        }
        $$('div[name=items]').remove();
        addSearchResult(para, "refresh")
        myApp.pullToRefreshDone();
    });
}

var totalPage = 1;
function addSearchResult(para, AddType) {
    App.showLoading();
    if (para.PageNumber > totalPage) {
        if (alreadyAlert) {
            Constant.alertNotification("往下已没有更多内容了，刷新试试！");
            $$('.infinite-scroll-preloader').remove();
            alreadyAlert = false;
        }
        App.hideLoading();
        return false;
    }
    $.ajax({
        url: Constant.contextUrl + "/mulanweb/common/visa/search",
        async: false,
        type: "post",
        dataType: "json",
        data: para,
        success: function (data) {
            if (data.DataList) {
                var template = $('#visaDataListModel').html();
                var compiledTemplate = Template7.compile(template);
                var htmlStr = compiledTemplate(data);
                if (AddType) {
                    $("#queryResultList").html(htmlStr);
                    currentPage = 1;
                } else {
                    $("#queryResultList").append(htmlStr);
                }
                if (data.TotalPage == data.PageNumber) {
                    $$('.infinite-scroll-preloader').remove();
                    alreadyAlert = true;
                }
                totalPage = data.TotalPage;
            }
            App.hideLoading();

        }
    }, para, function (data) {
    });
}


function changeButtomMenuPrice(id,price,priceOld){
    $("#reserve_visa_child_id").val(id);
    $("#lastPriceOld").html(priceOld);
    $("#lastPrice").html(price);
}

function saveVisaOrder(){
    App.showLoading();
    var phoneNumber = $("#collect_phone").val();
    var email = $("#collect_email").val();
    var couponCode = $("#collect-coupon").val();
    var remarks = $("#collect-remarks").val();
    var childId =  $("#reserve_visa_child_id").val();
    var amount = $("#collect_amount").val();
    var name = $("#collect_name").val();
    var para = {
        phoneNumber: phoneNumber,
        email: email,
        couponCode: couponCode,
        visaChildId: childId,
        remarks: remarks,
        amount:amount,
        name:name
    }
    $.post(Constant.contextUrl+'/mulanweb/wechat/visa_order/save', para, function (info) {
        if (info.message || info.AlertMessage) {
            Constant.alert(info.message || info.AlertMessage);
        }
        if (info.returnCode == 1) {
            var target = info.target;
            window.location.href=Constant.contextUrl+"/view/wxpay/confirm_pay.jsp?price=" + target.price + "&title=" + target.title + "&targetLogo=" + info.targetLogo + "&orderNumber=" + info.orderNumber+"&visaOrderTag=visaOrderTag";
        }
        App.hideLoading();
    });
}